import math
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from .item import *


class CGAIScene(QGraphicsScene):

    def __init__(self,scene_rect):
        super(CGAIScene, self).__init__()


        self.grid_size = 20     #网格尺寸
        self.grid_squares = 5   #网格数量

        self._color_background = QColor('#393939')   #背景颜色
        self._color_light = QColor('#2f2f2f')        #线颜色
        self._color_dark = QColor('#292929')

        self._pen_light = QPen(self._color_light)     #设置绘笔
        self._pen_light.setWidth(1)                   #绘笔宽度
        self._pen_dark = QPen(self._color_dark)       #绘笔颜色
        self._pen_dark.setWidth(2)                    #深色宽度

        self.setBackgroundBrush(self._color_background)
        # self.setSceneRect(0, 0, 500, 500)
        self.setSceneRect(scene_rect)

        self.nodes = []           #当前场景中所有节点
        self.edges = []           #当前场景中所有连线


    # def create_base_item(self,pos=None):
    #     item=CGAIItem()
    #     item.setPos(0,0) if not pos else item.setPos(pos)
    #     self.addItem(item)
    #     item.all_point_items()
    #
    # def test_item(self,pos=None):
    #     item=CGAIItem()
    #     item.setPos(0,0) if not pos else item.setPos(pos-item.offset_pos)
    #     self.addItem(item)





    def drawBackground(self, painter,rect):
        """
        重写父类，自定义背景颜色，同时绘制网格
        :param painter:
        :param rect:
        :return:
        """
        super().drawBackground(painter, rect)

        left = int(math.floor(rect.left()))      #获取scene的最左边 x坐标
        right = int(math.ceil(rect.right()))     #获取scene的最右边边 x坐标
        top = int(math.floor(rect.top()))        #获取scene的最上边 y坐标
        bottom = int(math.ceil(rect.bottom()))   #获取scene的最下边 y坐标

        first_left = left - (left % self.grid_size)
        first_top = top - (top % self.grid_size)

        lines_light, lines_dark = [], []
        for x in range(first_left, right, self.grid_size):
            if x % (self.grid_size * self.grid_squares) != 0:
                lines_light.append(QLine(x, top, x, bottom))
            else:
                lines_dark.append(QLine(x, top, x, bottom))

        for y in range(first_top, bottom, self.grid_size):
            if y % (self.grid_size * self.grid_squares) != 0:
                lines_light.append(QLine(left, y, right, y))
            else:
                lines_dark.append(QLine(left, y, right, y))

        # draw the lines
        painter.setPen(self._pen_light)
        if lines_light:
            # painter.drawLines(*lines_light)  #直接使用drawLines绘制多个线
            painter.drawLines(lines_light)  #直接使用drawLines绘制多个线

        painter.setPen(self._pen_dark)
        if lines_dark:
            # painter.drawLines(*lines_dark)
            painter.drawLines(lines_dark)
